const tips = require('../../utils/tips');
const auth = require('../../utils/auth');
const api = require('../../utils/api');
const countdownApi = require('../../utils/countdownApi');

Page({
  data: {
    userInfo: null,
    features: [
      {
        name: '作业',
        icon: '/assets/作业.png',
        path: '/pages/class/homework/index'
      },
      {
        name: '热门模板',
        icon: '/assets/热门模板.png',
        path: '/pages/class/templates/index'
      },
      {
        name: '通知',
        icon: '/assets/通知.png',
        path: '/pages/class/notice/index'
      },
      {
        name: '打卡',
        icon: '/assets/打卡.png',
        path: '/pages/class/checkin/index'
      }
    ],
    // 下拉刷新和上拉加载相关数据
    refresherTriggered: false,
    loading: false,
    noMore: false,
    // 倒数日数据
    upcomingCountdown: null,
    countdownList: [],        // 所有即将到期的倒数日列表
    currentCountdownIndex: 0, // 当前显示的倒数日索引
    countdownTimer: null,     // 轮播定时器
    // 触摸相关
    touchStartX: 0,           // 触摸开始X坐标
    touchStartY: 0,           // 触摸开始Y坐标
    touchStartTime: 0         // 触摸开始时间
  },
  onLoad() {
    console.log('班级页面加载');
    console.log('功能数据:', this.data.features);
    
    // 检查登录状态
    this.checkLoginStatus();
    
    // 确保数据正确设置
    this.setData({
      refresherTriggered: false,
      loading: false,
      noMore: false
    });
    
    // 加载倒数日数据
    this.loadCountdownData();
    
    console.log('页面数据加载完成');
  },

  // 检查登录状态
  checkLoginStatus() {
    if (!auth.isLoggedIn()) {
      console.log('用户未登录，跳转到登录页');
      auth.goToLogin();
      return;
    }
    
    const userInfo = auth.getUserInfo();
    this.setData({
      userInfo: userInfo
    });
    console.log('用户已登录:', userInfo);
  },

  onShow() {
    if (!wx.getStorageSync('hasVisited')) {
      wx.showModal({
        title: '欢迎使用',
        content: tips.welcome.firstVisit + '\n\n' + tips.welcome.guide,
        confirmText: '需要演示',
        cancelText: '不用啦',
        success(res) {
          wx.setStorageSync('hasVisited', true);
          if (res.confirm) {
            // 可跳转到AI出题或功能演示页
          }
        }
      });
    }
    
    // 刷新倒数日数据
    this.loadCountdownData();
  },

  onHide() {
    // 页面隐藏时停止轮播
    this.stopCountdownRotation();
  },

  onUnload() {
    // 页面卸载时停止轮播
    this.stopCountdownRotation();
  },
  onFeatureTap(e) {
    const path = e.currentTarget.dataset.path;
    if (path) {
      wx.navigateTo({ url: path });
    } else {
      wx.showToast({ title: '功能开发中', icon: 'none' });
    }
  },
  goPublish() {
    wx.navigateTo({ url: '/pages/class/publish/index' });
  },

  // 下拉刷新
  onRefresh() {
    console.log('下拉刷新');
    this.setData({
      refresherTriggered: true
    });
    
    // 这里可以添加实际的刷新逻辑
    setTimeout(() => {
      this.setData({
        refresherTriggered: false
      });
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 1500
      });
    }, 1500);
  },

  // 上拉加载更多
  onLoadMore() {
    console.log('上拉加载更多');
    if (this.data.loading || this.data.noMore) {
      return;
    }
    
    this.setData({
      loading: true
    });
    
    // 这里可以添加实际的加载更多逻辑
    setTimeout(() => {
      this.setData({
        loading: false,
        noMore: true // 暂时设置为没有更多数据
      });
    }, 1000);
  },

  // 跳转到首页
  goToHome() {
    wx.navigateTo({
      url: '/pages/home/home'
    });
  },

  // 跳转到倒数日页面
  goToCountdown() {
    wx.navigateTo({
      url: '/pages/countdown/countdown'
    });
  },

  // 跳转到班级课表页面
  goToSchedule() {
    wx.navigateTo({
      url: '/pages/schedule/schedule'
    });
  },

  // 跳转到客服页面
  goToService() {
    wx.showModal({
      title: '客服服务',
      content: '客服功能正在开发中，敬请期待！',
      showCancel: false
    });
  },

  // 跳转到发布页面
  goToPublish() {
    wx.navigateTo({
      url: '/pages/class/publish/index'
    });
  },

  // 跳转到设置页面
  goToSettings() {
    wx.showActionSheet({
      itemList: ['班级设置', '成员管理', '权限设置', '班级信息'],
      success: (res) => {
        const actions = ['班级设置', '成员管理', '权限设置', '班级信息'];
        wx.showToast({
          title: `${actions[res.tapIndex]}功能开发中`,
          icon: 'none'
        });
      }
    });
  },

  // 跳转到个人资料
  goToProfile() {
    const userInfo = this.data.userInfo;
    wx.showModal({
      title: '个人信息',
      content: `昵称：${userInfo.nickName || '未设置'}\nOpenID：${userInfo.openId || '未获取'}\n登录时间：${userInfo.createTime || '未知'}`,
      showCancel: false
    });
  },

  // 加载倒数日数据
  async loadCountdownData() {
    try {
      console.log('开始加载倒数日数据');
      const response = await countdownApi.getUpcoming();
      
      if (response && response.code === 200 && response.data && response.data.length > 0) {
        // 处理所有即将到期的事件
        const processedList = response.data.map(event => {
          const remainingDays = this.calculateRemainingDays(event.targetDate);
          return {
            id: event.id,
            eventName: event.eventName,
            targetDate: event.targetDate,
            remainingDays: remainingDays,
            creator: event.creator
          };
        });
        
        this.setData({
          countdownList: processedList,
          currentCountdownIndex: 0,
          upcomingCountdown: processedList[0]
        });
        
        console.log('倒数日数据加载成功，共', processedList.length, '个事件');
        
        // 启动轮播
        this.startCountdownRotation();
      } else {
        console.log('没有即将到期的倒数日事件');
        this.setData({
          countdownList: [],
          currentCountdownIndex: 0,
          upcomingCountdown: null
        });
        this.stopCountdownRotation();
      }
    } catch (error) {
      console.error('加载倒数日数据失败:', error);
      this.setData({
        countdownList: [],
        currentCountdownIndex: 0,
        upcomingCountdown: null
      });
      this.stopCountdownRotation();
    }
  },

  // 计算剩余天数
  calculateRemainingDays(targetDate) {
    const today = new Date();
    const target = new Date(targetDate);
    const diffTime = target - today;
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays;
  },

  // 启动倒数日轮播
  startCountdownRotation() {
    // 清除之前的定时器
    this.stopCountdownRotation();
    
    // 如果只有一个或没有事件，不需要轮播
    if (this.data.countdownList.length <= 1) {
      return;
    }
    
    console.log('启动倒数日轮播，每5秒切换一次');
    
    this.data.countdownTimer = setInterval(() => {
      this.nextCountdown();
    }, 5000); // 5秒
  },

  // 停止倒数日轮播
  stopCountdownRotation() {
    if (this.data.countdownTimer) {
      clearInterval(this.data.countdownTimer);
      this.data.countdownTimer = null;
      console.log('停止倒数日轮播');
    }
  },

  // 切换到下一个倒数日
  nextCountdown() {
    const { countdownList, currentCountdownIndex } = this.data;
    
    if (countdownList.length === 0) {
      return;
    }
    
    // 计算下一个索引
    const nextIndex = (currentCountdownIndex + 1) % countdownList.length;
    
    // 更新当前显示的倒数日
    this.setData({
      currentCountdownIndex: nextIndex,
      upcomingCountdown: countdownList[nextIndex]
    });
    
    console.log('切换到倒数日:', countdownList[nextIndex].eventName, '剩余', countdownList[nextIndex].remainingDays, '天');
  },

  // 手动切换到下一个倒数日（点击事件）
  onCountdownTap() {
    if (this.data.countdownList.length > 1) {
      this.nextCountdown();
    } else {
      // 如果只有一个或没有事件，直接跳转到倒数日页面
      this.goToCountdown();
    }
  },

  // 触摸开始
  onTouchStart(e) {
    const touch = e.touches[0];
    this.setData({
      touchStartX: touch.clientX,
      touchStartY: touch.clientY,
      touchStartTime: Date.now()
    });
    console.log('触摸开始:', touch.clientX, touch.clientY);
  },

  // 触摸结束
  onTouchEnd(e) {
    const touch = e.changedTouches[0];
    const deltaX = touch.clientX - this.data.touchStartX;
    const deltaY = touch.clientY - this.data.touchStartY;
    const deltaTime = Date.now() - this.data.touchStartTime;
    
    console.log('触摸结束:', {
      deltaX: deltaX,
      deltaY: deltaY,
      deltaTime: deltaTime
    });
    
    // 判断是否为有效的滑动
    if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 50 && deltaTime < 500) {
      if (this.data.countdownList.length > 1) {
        if (deltaX > 0) {
          // 向右滑动，切换到上一个
          this.previousCountdown();
        } else {
          // 向左滑动，切换到下一个
          this.nextCountdown();
        }
      }
    } else if (Math.abs(deltaX) < 20 && Math.abs(deltaY) < 20 && deltaTime < 300) {
      // 点击事件，切换到下一个
      this.onCountdownTap();
    }
  },

  // 切换到上一个倒数日
  previousCountdown() {
    const { countdownList, currentCountdownIndex } = this.data;
    
    if (countdownList.length === 0) {
      return;
    }
    
    // 计算上一个索引（循环）
    const prevIndex = currentCountdownIndex === 0 ? countdownList.length - 1 : currentCountdownIndex - 1;
    
    // 更新当前显示的倒数日
    this.setData({
      currentCountdownIndex: prevIndex,
      upcomingCountdown: countdownList[prevIndex]
    });
    
    console.log('切换到上一个倒数日:', countdownList[prevIndex].eventName, '剩余', countdownList[prevIndex].remainingDays, '天');
    
    // 重置定时器
    this.resetCountdownTimer();
  },

  // 重置轮播定时器
  resetCountdownTimer() {
    if (this.data.countdownList.length > 1) {
      this.stopCountdownRotation();
      this.startCountdownRotation();
    }
  }
});

